package com.lzx.iteam;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.R;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.widget.ChatGroupLayout;
import com.lzx.iteam.widget.PersonVO;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

public class BatchSendSmsActivity extends Activity implements ChatGroupLayout.OnChangeListener{

    public static final String NUMBERS_KEY = "numbers";
    public static final String TEXT_KEY = "text_key";
    
    public static final int SEND_PROGRESS = 0;
    private ArrayList<PersonVO> persons = new ArrayList<PersonVO>();
    
    private EditText contentET;
    private Button sendBT;
    private ListView personsList;
    private ChatGroupLayout cg;
    private PersonsAdapter adapter;
    private Bitmap deleteIcon;
    private String textArea;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.batch_send_sms);
        sendBT = (Button) findViewById(R.id.batch_send_sms_send);
        parseIntent();
        if(persons.size()>0){
            PersonVO first = persons.get(0);
            String firstName = ContactsDBReader.getContactNameByContactId(getContentResolver(), first.id);
            if(firstName==null){
                firstName = first.number;
            }
            first.name = firstName;
            first.hasName = 1;
            TextView tv = (TextView) findViewById(R.id.batch_send_sms_more);
            tv.setText(firstName+" +"+(persons.size()-1));
        }
        contentET = (EditText) findViewById(R.id.batch_send_sms_content);
        contentET.setText(textArea);
        contentET.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                cg.setSelect(1);
            }
        });
        contentET.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                
            }
            
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }
            
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    sendBT.setEnabled(false);
                }else{
                    sendBT.setEnabled(true);
                }
            }
        });
        cg = (ChatGroupLayout) findViewById(R.id.batchsms_container);
        cg.setListener(this);
        deleteIcon = BitmapFactory.decodeResource(getResources(), R.drawable.edit_contact_deleteh);
        personsList = (ListView) cg.findViewById(R.id.batchsms_persons_list);
        adapter = new PersonsAdapter();
        personsList.setAdapter(adapter);
        ImageView shadowIV = (ImageView) cg.findViewById(R.id.batchsms_shadow);
        GradientDrawable leftShadow = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, new int[]{Color.argb(100, 0, 0, 0),Color.argb(80, 0, 0, 0),Color.argb(10, 0, 0, 0),Color.argb(0, 0, 0, 0)});
        leftShadow.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        shadowIV.setImageDrawable(leftShadow);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        deleteIcon.recycle();
    }
    
   
    
    public void cancel(View view){
        finish();
    }
    
    public void personsOperation(View view){
        cg.setSelect(0);
        
    }
    
    
    
    public void send(View view){
        view.setEnabled(false);
        String content = contentET.getText().toString();
        Intent startService = new Intent(this,BatchSendSmsService.class);
        startService.putParcelableArrayListExtra("persons", persons);
        startService.putExtra("content", content);
        startService(startService);
        finish();
    }    
   
    
    public void parseIntent(){
        Intent intent = getIntent();
        if(intent.hasExtra(TEXT_KEY)){
            textArea = intent.getStringExtra(TEXT_KEY);
            sendBT.setEnabled(true);
        }else{
            textArea = "";
        }
        if(intent.hasExtra(NUMBERS_KEY)){
            String arrStr = intent.getStringExtra(NUMBERS_KEY);
            try {
                JSONArray arr = new JSONArray(arrStr);
                for(int i=0;i<arr.length();i++){
                    PersonVO pv = new PersonVO();
                    JSONObject obj = (JSONObject) arr.get(i);
                    Iterator<String> iterator = obj.keys();
                    if(iterator.hasNext()){
                        String key = iterator.next();
                        pv.id = Long.parseLong(key);
                        pv.number = obj.getString(key);
                        persons.add(pv);
                    }
                    
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            
        }
    }
    
    
    public class PersonsAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return persons.size();
        }

        @Override
        public Object getItem(int arg0) {

            return persons.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {

            return arg0;
        }

        @Override
        public View getView(int pos, View convertView, ViewGroup arg2) {
            if(convertView==null){
                convertView = getLayoutInflater().inflate(R.layout.batchsms_item, null);
                ViewHolder vh = new ViewHolder();
                vh.nameTV = (TextView) convertView.findViewById(R.id.batchsms_name);
                vh.numberTv = (TextView) convertView.findViewById(R.id.batchsms_number);
                vh.deleteBT = (ImageButton) convertView.findViewById(R.id.batchsms_delete);
                convertView.setTag(vh);
            }
            bindView(convertView, pos);
            return convertView;
        }
        
        public void bindView(View convertView,final int pos){
            PersonVO person = persons.get(pos);
            if(person.hasName==0){
                String name = ContactsDBReader.getContactNameByContactId(getContentResolver(), person.id);
                if(name==null){
                    name = person.number;
                }
                person.name = name;
                person.hasName = 1;
            }
            ViewHolder vh = (ViewHolder) convertView.getTag();
            vh.nameTV.setText(person.name);
            vh.numberTv.setText(person.number);
            vh.deleteBT.setImageBitmap(deleteIcon);
            vh.deleteBT.setOnClickListener(new View.OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    if(persons.size()==1){
                        Toast.makeText(BatchSendSmsActivity.this, "至少有一个联系人", Toast.LENGTH_LONG).show();
                        return;
                    }
                    persons.remove(pos);
                    notifyDataSetChanged();
                }
            });
        }
        
    }
    
    class ViewHolder{
        TextView nameTV;
        TextView numberTv;
        ImageButton deleteBT;
    }

    @Override
    public void onChange(int index) {
        if(index==1){
            TextView tv = (TextView) findViewById(R.id.batch_send_sms_more);
            if(persons.size() != 0){
                tv.setText(persons.get(0).name+"+"+(persons.size()-1)); 
            }
        }else{
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if(im.isActive()){
                im.hideSoftInputFromWindow(contentET.getWindowToken(), 0);
            }
        }
    }
    
    
    
}
